#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
福特网站专用Cookie处理器
基于深度分析发现的特定CSS类进行精确处理
"""

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, ElementClickInterceptedException, NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


class ImprovedCookieHandler:
    """改进的Cookie处理器 - 专门针对福特网站"""
    
    def __init__(self, driver):
        """
        初始化Cookie处理器
        
        Args:
            driver: Selenium WebDriver实例
        """
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)
    
    def handle_ford_cookie_consent(self):
        """
        处理福特网站的Cookie同意弹窗
        基于深度分析发现的具体CSS类名
        """
        print("🍪 开始处理福特网站Cookie弹窗...")
        
        try:
            # 等待页面稳定
            time.sleep(2)
            
            # 阶段1：检测Cookie弹窗容器
            cookie_containers_found = self.detect_cookie_containers()
            
            if not cookie_containers_found:
                print("ℹ️  未检测到Cookie弹窗容器")
                return False
            
            # 阶段2：尝试查找并点击同意按钮
            consent_success = self.find_and_click_consent_button()
            
            if consent_success:
                # 阶段3：验证弹窗是否消失
                time.sleep(2)
                removal_success = self.verify_cookie_removal()
                
                if not removal_success:
                    # 阶段4：强制移除Cookie弹窗
                    print("⚠️  同意按钮点击后弹窗仍存在，尝试强制移除...")
                    self.force_remove_cookie_dialogs()
                
                return True
            else:
                # 阶段4：如果找不到同意按钮，直接强制移除
                print("⚠️  未找到同意按钮，尝试强制移除Cookie弹窗...")
                self.force_remove_cookie_dialogs()
                return True
                
        except Exception as e:
            print(f"❌ Cookie处理过程出错: {e}")
            # 最后尝试：强制移除
            try:
                self.force_remove_cookie_dialogs()
                return True
            except Exception as force_error:
                print(f"❌ 强制移除也失败: {force_error}")
                return False
    
    def detect_cookie_containers(self):
        """检测Cookie弹窗容器"""
        print("🔍 检测Cookie弹窗容器...")
        
        # 基于深度分析发现的具体CSS类
        ford_cookie_selectors = [
            '.styles__CookieDisclaimerWrapper-sc-dx4a8y-0.bByYil',
            '.styles__CookieDisclaimerContent-sc-dx4a8y-3.hUJXDq',
            '[class*="styles__CookieDisclaimer"]',
            '[class*="CookieDisclaimer"]',
            'div[role="dialog"][class*="Cookie"]',
            'div[role="dialog"][class*="cookie"]'
        ]
        
        containers_found = []
        
        for selector in ford_cookie_selectors:
            try:
                elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                for element in elements:
                    if element.is_displayed():
                        containers_found.append({
                            'element': element,
                            'selector': selector,
                            'class': element.get_attribute('class'),
                            'text': element.text.strip()[:100]
                        })
                        print(f"  ✓ 发现Cookie容器: {selector}")
                        print(f"    class: {element.get_attribute('class')}")
            except Exception as e:
                continue
        
        print(f"  总共发现 {len(containers_found)} 个Cookie容器")
        return containers_found
    
    def find_and_click_consent_button(self):
        """查找并点击同意按钮"""
        print("🔍 查找Cookie同意按钮...")
        
        # 福特网站可能的同意按钮选择器
        consent_button_selectors = [
            # 通用的同意按钮
            'button[data-testid="accept-all-cookies"]',
            'button[id*="accept"]',
            'button[class*="accept"]',
            'button[aria-label*="accept" i]',
            'button[aria-label*="Accept" i]',
            # 在Cookie容器内的按钮
            '.styles__CookieDisclaimerWrapper-sc-dx4a8y-0 button',
            '.styles__CookieDisclaimerContent-sc-dx4a8y-3 button',
            '[class*="CookieDisclaimer"] button',
            '[role="dialog"] button',
            # 文本匹配
            'button',
            'a[role="button"]'
        ]
        
        for selector in consent_button_selectors:
            try:
                buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)
                
                for button in buttons:
                    if self.is_consent_button(button):
                        try:
                            # 尝试点击
                            self.click_button_safely(button)
                            print(f"  ✓ 成功点击同意按钮: '{button.text.strip()}'")
                            return True
                        except Exception as click_error:
                            print(f"  ✗ 点击按钮失败: {click_error}")
                            continue
                            
            except Exception as selector_error:
                continue
        
        print("  ❌ 未找到可点击的同意按钮")
        return False
    
    def is_consent_button(self, button):
        """判断是否是同意按钮"""
        if not button.is_displayed() or not button.is_enabled():
            return False
        
        button_text = button.text.strip().lower()
        button_class = (button.get_attribute('class') or '').lower()
        button_aria_label = (button.get_attribute('aria-label') or '').lower()
        
        # 同意相关关键词
        consent_keywords = [
            'accept', 'agree', 'allow', 'ok', 'continue', 
            'consent', 'yes', 'i agree', 'accept all',
            'accept cookies', 'allow cookies'
        ]
        
        # 拒绝相关关键词（要避免）
        reject_keywords = [
            'reject', 'decline', 'refuse', 'deny', 'no',
            'manage', 'settings', 'preferences', 'customize'
        ]
        
        # 检查是否包含同意关键词
        has_consent_keyword = any(keyword in button_text for keyword in consent_keywords)
        has_consent_keyword = has_consent_keyword or any(keyword in button_class for keyword in consent_keywords)
        has_consent_keyword = has_consent_keyword or any(keyword in button_aria_label for keyword in consent_keywords)
        
        # 检查是否包含拒绝关键词
        has_reject_keyword = any(keyword in button_text for keyword in reject_keywords)
        has_reject_keyword = has_reject_keyword or any(keyword in button_class for keyword in reject_keywords)
        has_reject_keyword = has_reject_keyword or any(keyword in button_aria_label for keyword in reject_keywords)
        
        return has_consent_keyword and not has_reject_keyword
    
    def click_button_safely(self, button):
        """安全地点击按钮"""
        try:
            # 滚动到按钮可见
            self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
            time.sleep(0.5)
            
            # 尝试普通点击
            button.click()
        except ElementClickInterceptedException:
            # 如果普通点击被拦截，使用JavaScript点击
            self.driver.execute_script("arguments[0].click();", button)
    
    def verify_cookie_removal(self):
        """验证Cookie弹窗是否已移除"""
        print("🔍 验证Cookie弹窗移除状态...")
        
        # 检查之前发现的Cookie容器是否还存在
        cookie_selectors = [
            '.styles__CookieDisclaimerWrapper-sc-dx4a8y-0',
            '.styles__CookieDisclaimerContent-sc-dx4a8y-3',
            '[class*="CookieDisclaimer"]',
            'div[role="dialog"][class*="Cookie"]'
        ]
        
        visible_cookies = 0
        for selector in cookie_selectors:
            try:
                elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                for element in elements:
                    if element.is_displayed():
                        visible_cookies += 1
                        print(f"  ⚠️  仍有可见的Cookie元素: {selector}")
            except Exception:
                continue
        
        if visible_cookies == 0:
            print("  ✓ Cookie弹窗已完全移除")
            return True
        else:
            print(f"  ❌ 仍有 {visible_cookies} 个可见的Cookie元素")
            return False
    
    def force_remove_cookie_dialogs(self):
        """强制移除Cookie弹窗"""
        print("🔧 强制移除Cookie弹窗...")
        
        # 所有可能的Cookie相关选择器
        removal_selectors = [
            '.styles__CookieDisclaimerWrapper-sc-dx4a8y-0',
            '.styles__CookieDisclaimerContent-sc-dx4a8y-3',
            '[class*="styles__CookieDisclaimer"]',
            '[class*="CookieDisclaimer"]',
            'div[role="dialog"][class*="Cookie"]',
            'div[role="dialog"][class*="cookie"]',
            '[class*="cookie-banner"]',
            '[class*="cookie-notice"]',
            '[id*="cookie"]'
        ]
        
        removed_count = 0
        for selector in removal_selectors:
            try:
                elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                for element in elements:
                    if element.is_displayed():
                        # 使用JavaScript强制移除
                        self.driver.execute_script("""
                            arguments[0].style.display = 'none';
                            arguments[0].style.visibility = 'hidden';
                            arguments[0].remove();
                        """, element)
                        removed_count += 1
                        print(f"  ✓ 强制移除元素: {selector}")
            except Exception as e:
                continue
        
        # 额外的清理：移除可能阻止点击的overlay
        try:
            self.driver.execute_script("""
                // 移除所有可能的Cookie相关overlay
                var overlays = document.querySelectorAll('[class*="overlay"], [class*="backdrop"], [class*="modal"]');
                overlays.forEach(function(overlay) {
                    if (overlay.style.zIndex > 1000) {
                        overlay.remove();
                    }
                });
                
                // 重置body的overflow样式
                document.body.style.overflow = 'auto';
            """)
            print("  ✓ 执行额外的页面清理")
        except Exception:
            pass
        
        print(f"  总共强制移除了 {removed_count} 个Cookie相关元素")
        
        # 等待页面稳定
        time.sleep(1)


def test_cookie_handler():
    """测试Cookie处理器"""
    url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-D3&paint=PN4A7&planId=c"
    
    print("福特Cookie处理器测试")
    print("=" * 50)
    
    # 初始化WebDriver
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--window-size=1920,1080')
    
    try:
        from webdriver_manager.chrome import ChromeDriverManager
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=options)
    except Exception:
        driver = webdriver.Chrome(options=options)
    
    try:
        print(f"访问页面: {url}")
        driver.get(url)
        
        # 等待20秒让页面完全加载
        print("等待页面完全加载（20秒）...")
        for i in range(20):
            time.sleep(1)
            if i % 5 == 4:
                print(f"  加载中... {i+1}/20秒")
        
        # 使用改进的Cookie处理器
        cookie_handler = ImprovedCookieHandler(driver)
        success = cookie_handler.handle_ford_cookie_consent()
        
        if success:
            print("✅ Cookie处理成功！")
            
            # 测试是否可以点击车型
            print("\n测试车型点击...")
            try:
                model_element = driver.find_element(By.CSS_SELECTOR, 'div[data-cy="Titanium"]')
                model_element.click()
                print("✅ 车型点击成功！")
            except Exception as e:
                print(f"❌ 车型点击失败: {e}")
        else:
            print("❌ Cookie处理失败")
        
        input("按Enter键关闭浏览器...")
        
    finally:
        driver.quit()


if __name__ == "__main__":
    test_cookie_handler()